el-card<template>
  <div class="by">
    <div class="by-container">
      <el-card
        style="
          width: 1200px;
          margin: 0 auto;
          background-color: rgb(249, 249, 249) !important;
        "
      >
        <div class="container">
          <div class="left">
            <div
              style="
                margin: 20px 0;
                text-align: center;
                font-size: 30px;
                font-weight: 700;
              "
            >
              {{ detail.title }}
              {{ detail.isPay == 0 ? "(免费)" : `(￥${detail.payPrice})` }}
            </div>
            <el-carousel indicator-position="outside">
              <el-carousel-item
                v-for="(item, index) in carouselsImages"
                :key="index"
              >
                <el-image :src="item" :preview-src-list="[item]"> </el-image>
              </el-carousel-item>
            </el-carousel>
          </div>
          <div class="right">
            <div class="top">
              <el-progress 
      v-if="downloadProgress > 0" 
      :percentage="downloadProgress"
      :stroke-width="20"
      status="success">
    </el-progress>
              <el-row>
                <el-button
                  type="primary"
                  icon="el-icon-bottom"
                  style="width: 100%"
                  v-if="showBtn"
                  @click="download"
                  >下载资源</el-button
                >
              </el-row>
              <el-row style="margin: 18px; text-align: center">
                <el-col :span="12">
                  下载数量
                  <i class="iconfont"> &#xe63c; </i>{{ detail.downloadCount }}
                </el-col>
                <el-col :span="12">
                  查看数量
                  <i class="iconfont"> &#xe60b; </i>{{ detail.showCount }}
                </el-col>
              </el-row>
            </div>

            <div class="bottom">
              <div
                style="text-align: center; font-size: 20px; font-weight: 700"
              >
                站主推荐
              </div>
              <div class="recommend">
                <div
                  v-for="item in detail.recommendResources"
                  :key="item.id"
                  class="resource-title"
                  @click="gotoDetail(item)"
                >
                  {{ item.title }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 展示视频 -->
        <div
          class="link_video"
          v-if="detail.linkVideoUrl != '' || detail.videoUrl != ''"
        >
          <div class="title">项目视频展示</div>
          <iframe
            v-if="detail.linkVideoUrl != null && detail.linkVideoUrl != ''"
            :src="detail.linkVideoUrl"
            scrolling="no"
            border="0"
            frameborder="no"
            framespacing="0"
            allowfullscreen="true"
            height="500px"
            width="1200px"
          ></iframe>

          <iframe
            v-if="detail.videoUrl != null && detail.videoUrl != ''"
            :src="detail.videoUrl"
            scrolling="no"
            border="0"
            frameborder="no"
            framespacing="0"
            allowfullscreen="true"
            height="500px"
            width="1200px"
          ></iframe>
        </div>

        <div>
          <div class="title">项目介绍及大图预览</div>
          <div
            v-html="this.content"
            v-viewer
            class="markdown-body html-content"
          ></div>
        </div>
      </el-card>
    </div>

    <goback :right="36" :bottom="76"></goback>

    <el-dialog title="购买资源" :visible.sync="showDetail" width="45%">
      <div>
        <div>
          请输入邮箱：<el-input v-model="email" placeholder=""></el-input>
        </div>
        <div style="margin-top: 10px">
          请选择支付方式：
          <el-radio v-model="payType" :label="1">支付宝支付</el-radio>
          <el-radio v-model="payType" :label="2">微信支付</el-radio>
        </div>
      </div>
      <div style="margin-top: 10px">
        <p style="color: red">注意：请输入正确的邮箱，否则无法下载资源！</p>
        <p style="color: red">
          支付成功后会以邮箱的方式发送对应的下载链接，如链接失效请提供对应的凭证反馈，站主会及时处理~
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDetail = false">取 消</el-button>
        <el-button type="primary" @click="submit">支付</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import goback from "@/components/getback/getback.vue";
import axios from "axios";
import { marked } from "marked";
export default {
  name: "WorkspaceJsonResourcesDetail",

  data() {
    return {
      carouselsImages: [], //轮播图
      detail: {},
      showDetail: false,
      email: "",
      payType: 1,
      downloadUrl: process.env.VUE_APP_BASE_API + "/downLoad",
      url: process.env.VUE_APP_ARTICLE_PATH,
      downloadProgress: 0,
      showBtn: true,
    };
  },
  computed: {
    content() {
      var reg = new RegExp("<pre", "g");
      var content = marked(this.detail.detailHtml);
      var str = content.replace(reg, `<pre class='line-numbers'`);
      return str;
    },
    UserName() {
      return this.$store.state.UserInfo.nickname;
    },
  },
  components: {
    goback,
  },
  mounted() {
    if (this.$route.query.id) {
      this.getDetail(this.$route.query.id);
    }
  },

  methods: {
    gotoDetail(item){
      this.getDetail(item.id);
    },
    getDetail(id) {
      this.$api.resource.getResource(id).then((res) => {
        if (res.code == 200) {
          this.carouselsImages = res.data.carousels.split(",");
          this.detail = res.data;
        } else {
          this.$message.error(res.message);
          this.$router.push(-1);
        }
      });
    },
    download() {
      // 判断是否登录
      if (this.UserName == "" || this.UserName == null) {
        this.$message.error("请先登录！");
        return;
      }
      // 免费资源的下载逻辑
      if (this.detail.isPay == 0) {
        this.showBtn=false
        this.downloadShow()
      } else {
        // 判断是否登录
        if (this.UserName == "" || this.UserName == null) {
          this.$message.error("请先登录！");
          return;
        }
        this.showDetail = true;
      }
    },

    downloadShow() {
      axios({
        method: "get",
        url: this.url + this.downloadUrl + "?id=" + this.detail.id,
        responseType: "blob",
        headers: {
          Authorization: this.$store.state.token,
        },
        onDownloadProgress: (progressEvent) => {
          // 计算下载进度百分比
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          // 假设使用Element UI的Progress组件显示进度
          this.downloadProgress = percentCompleted;
        },
      })
        .then((response) => {
          // 下载完成，重置进度
          this.downloadProgress = 0;
          // 获取文件名
          const contentDisposition = response.headers["content-disposition"];
          let fileName = "download";
          if (contentDisposition) {
            const filenameMatch = contentDisposition.match(/filename=(.*)/);
            if (filenameMatch) {
              fileName = decodeURIComponent(filenameMatch[1]);
            }
          }
          // 创建Blob对象并下载
          const blob = new Blob([response.data]);
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        })
        .catch((error) => {
          // 发生错误时重置进度
          this.downloadProgress = 0;

          if (error.response) {
            const reader = new FileReader();
            reader.onload = () => {
              const errorMessage = reader.result;
              alert(errorMessage);
            };
            reader.readAsText(error.response.data);
          } else {
            alert("下载失败，请稍后重试");
          }
        }).finally(() => {
          this.showBtn=true
        });
    },
    submit() {
      if (this.email == "") {
        this.$message.error("请输入邮箱！");
        return;
      }
      this.$api.resource.pay(this.detail.id, this.email).then((res) => {
        if (res.code == 200) {
          if (res.code == 200) {
            const div = document.createElement("div");
            div.innerHTML = res.data;
            document.body.appendChild(div);
            document.forms[0].submit();
          }
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.by {
  /* https://blog-chen.oss-cn-shanghai.aliyuncs.com/bolg/2024-10-12/0f589a128b0648399145d02b36c86672.jpg */
  background: url("https://blog-chen.oss-cn-shanghai.aliyuncs.com/bolg/2024-10-12/0f589a128b0648399145d02b36c86672.jpg")
    no-repeat;
  /* https://blog-chen.oss-cn-shanghai.aliyuncs.com/bolg/2024-10-12/46785555990c4b209fb8495463fa7f69.jpg */
  /* background: url("https://blog-chen.oss-cn-shanghai.aliyuncs.com/bolg/2024-10-12/46785555990c4b209fb8495463fa7f69.jpg") no-repeat; */
  width: 100%;
  min-height: 100vh;
  background-size: cover;
  background-attachment: fixed;
  overflow: hidden;
  z-index: 10;
  position: relative;
}
ul {
  list-style: none !important;
}

.title {
  font-size: 30px;
  font-weight: 700;
  text-align: center;
  margin: 10px 0;
}

.by-container {
  margin-top: 80px;
}

.resource-title {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的文本 */
  text-overflow: ellipsis; /* 使用省略号表示被隐藏的文本 */
}

.resource-title:hover{
  color: #78b6f7;
}
.container {
  display: flex;
}

.left {
  width: 70%;
  height: 500px;
  padding: 5px;
  background-color: #fff;
}

.right {
  width: 30%;
  margin-left: 20px;

  /* background-color: #fff; */
  .top {
    height: 100px;
    background-color: #fff;
  }

  .bottom {
    margin-top: 20px;
    background-color: #fff;
    height: 390px;
  }
}

.recommend {
  margin-top: 10px;
  overflow: auto;

  div {
    cursor: pointer;
    height: 30px;
    line-height: 30px;
    font-size: 15px;
    width: 100%;
    border-top: 1px solid #ccc;
  }
}

.link_video {
  margin: 20px;
}

/deep/ .el-carousel__container {
  position: relative !important;
  height: 387px !important;
}

.el-image {
  height: 387px;
}

/deep/ .markdown-body {
  // background-color: #f8f8f8 !important;
  padding: 0 5px;
  // box-shadow: 0 10px 10px gainsboro;
  font-size: 15px;

  blockquote {
    border-left: 5px solid #78b6f7;
    padding: 10px;
  }

  pre {
    background: #272822 !important;
  }
  li code {
    padding: 8px;
    color: rgb(245, 125, 125) !important;
    font-size: 15px;
  }
   code {
    padding: 8px;
    color: rgb(245, 238, 238) !important;
    font-size: 15px;
  }
  img{
    width: 100% !important;
  }
}
</style>